/*
 * Public Credit Information Sharing Platform(PCISP).
 * Copyright (c) 2019-2020 jsxzkingdee and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * Please visit https://www.zhengxinsoft.com if you need additional information or have any questions.
 */

package com.platform.core.limit.filter;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.util.stream.LongStream;

/**
 * Description: 布隆缓存过滤器
 *
 * @author libin created on 2020/5/8.
 */
@SuppressWarnings("UnstableApiUsage")
@Component
public class BloomCacheFilter {

    public static BloomFilter<Long> bloomFilter = null;

    @PostConstruct
    public void init(){
        bloomFilter = BloomFilter.create(Funnels.longFunnel(), 100000);
        LongStream.rangeClosed(0, 10000).forEach(idx ->bloomFilter.put(idx));
    }

    public static boolean mightContain(long key){
        return bloomFilter.mightContain(key);
    }

    public static void main(String[] args) {
        int capacity = 1000000;
        long key = 6666;
        bloomFilter = BloomFilter.create(Funnels.longFunnel(), capacity);
        for (long i = 0; i < capacity; i++) {
            bloomFilter.put(i);
        }
        // 返回计算机最精确的时间，单位微妙
        long start = System.nanoTime();

        if (bloomFilter.mightContain(key)) {
            System.out.println("成功过滤到" + key);
        }
        long end = System.nanoTime();
        System.out.println("布隆过滤器消耗时间:" + (end - start));
        int sum = 0;
        for (long i = capacity + 20000; i < capacity + 30000; i++) {
            if (bloomFilter.mightContain(i)) {
                sum = sum + 1;
            }
        }
        //0.03
        //设置保留位数
        DecimalFormat df=new DecimalFormat("0.00");
        System.out.println("错判率为:" + df.format((float)sum/10000));
    }
}
